package com.qhit.controller;

import com.qhit.pojo.Tourist;
import com.qhit.service.TouristService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @program: lyb
 * @description: ll
 * @author: DYF
 * @create: 2020-10-22 09:33
 */
@Controller
@RequestMapping("/tourist")
public class TouristController {

    @Autowired
    private TouristService touristService;

    @RequestMapping("/list")
    public String list(Model m ,String keywords
            , @RequestParam(defaultValue = "1",required = false) Integer page
            , @RequestParam(defaultValue = "2",required = false) Integer pageSize){
        HashMap hashMap = new HashMap();
        hashMap.put("keywords",keywords);

        hashMap.put("page",page);
        hashMap.put("start",(page-1)*pageSize);
        hashMap.put("pageSize",pageSize);

        List<Tourist> tourist= touristService.getList(hashMap);
        long total= touristService.getListCount(hashMap);

        hashMap.put("totalPage",(total%pageSize==0)?(total/pageSize):(total/pageSize+1));

        m.addAttribute("touristList",tourist);
        m.addAttribute("myParams",hashMap);
        return "tourist/list";
    }


    @RequestMapping("/toAdd")
    public String toAdd(){
        return "tourist/add";
    }

    @RequestMapping(value = "/add",method= RequestMethod.POST)
    public String add(Tourist tourist,Model m){
        tourist.setId(UUID.randomUUID().toString());
        int result=touristService.add(tourist);
        if (result>0){
            m.addAttribute("msg","添加成功");
        }else {
            m.addAttribute("msg","添加失败");
        }
        return "tourist/msg";
    }

    @RequestMapping("/toEdit")
    public String toEdit(String id,Model m){
        Tourist g= touristService.getTouristById(id);
        m.addAttribute("tourist",g);

        return "tourist/edit";
    }

    @RequestMapping(value = "/edit",method= RequestMethod.POST)
    public String edit(Tourist tourist,Model m){
        int result=touristService.edit(tourist);
        if (result>0){
            m.addAttribute("msg","更新成功");
        }else {
            m.addAttribute("msg","更新失败");
        }
        return "tourist/msg";
    }

    @RequestMapping(value = "/del",method= RequestMethod.GET)
    public String del(String id,Model m){
        int result=touristService.del(id);
        if (result>0){
            m.addAttribute("msg","删除成功");
        }else {
            m.addAttribute("msg","删除失败");
        }
        return "tourist/msg";
    }

}
